/*
	gen_table.cc	Game Table Generator
	Copyright (c) 2003, 2004 Kriang Lerdsuwanakij
	email:		lerdsuwa@users.sourceforge.net

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "config.h"

#include <exception>
#include <stdexcept>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>

#include "gtstream.h"

#ifdef _
#undef _
#endif

#ifdef N_
#undef N_
#endif

#include <libintl.h>
#define _(x) gettext(x)
#define N_(x) x

// Grab version number in VERSION variable
// Use same version number as main GRhino program
#undef VERSION
const char *
#include "scripts/version"
;

const char *prog_name = "gen_table";
const char *prog_ver = VERSION;

// Counting bit algorithm from
//   http://www.caam.rice.edu/~dougm/twiddle/BitCount.html
int slow_count_bits(int x)
{
	int count = 0;
	while (x) {
		++count;
		x &= x-1;
	}
	return count;
}

int	main_real()
{
					// Generate header
	std::ofstream ofs("table-dat.h");
	ofs << "/* Generated by gen_table.  */\n\n";

					// Generate start board
	ofs << "char bit_count_table[256] = {\n";

	for (int i = 0; i < 16; ++i) {
		ofs << '\t';
		for (int j = 0; j < 16; ++j) {
			int num = i*16 + j;
			ofs << slow_count_bits(num);
			if (num < 255)
				ofs << ", ";
		}
		ofs << '\n';
	}
	ofs << "};\n\n";
	return 0;
}

int main()
{
	try {
		return main_real();
	}
	catch (std::exception &e) {
		std::cout << std::flush;
		gtout(std::cerr, _("%$: %$\n")) << prog_name << e.what();
	}
	catch (const char *s) {
		std::cout << std::flush;
		gtout(std::cerr, _("%$: exception %$\n")) << prog_name << s;
	}
	catch (...) {
		std::cout << std::flush;
		gtout(std::cerr, _("%$: unknown exception\n")) << prog_name;
	}
	return 1;
}
